package com.polaris.live.ui.party.fragment

import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.CollectionUtils
import com.blankj.utilcode.util.ScreenUtils
import com.blankj.utilcode.util.SnackbarUtils.dismiss
import com.bumptech.glide.Glide
import com.gyf.immersionbar.ImmersionBar
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.enums.PopupPosition
import com.polaris.live.R.drawable
import com.polaris.live.cache.CommonCache
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.constant.PagConst
import com.polaris.live.common.ext.autoDp
import com.polaris.live.common.ext.dp
import com.polaris.live.common.ext.formatNumberWithK
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.JsonUtils
import com.polaris.live.common.util.NavigationBarUtils
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.common.util.ViewUtils
import com.polaris.live.constant.LiveConst
import com.polaris.live.constant.UserConst
import com.polaris.live.databinding.FragmentPartySpectatorBinding
import com.polaris.live.dialog.GlobalDialogManager
import com.polaris.live.dialog.SendFreeGiftSelectDialog
import com.polaris.live.dialog_fragment.MusicPopup
import com.polaris.live.dialog_fragment.RoomInvitationFragmentDialog
import com.polaris.live.dialog_fragment.magiclamp.MagicLampPopup
import com.polaris.live.floating.FloatingService
import com.polaris.live.floating.FloatingWindowManager
import com.polaris.live.im.manager.ImLiveManager
import com.polaris.live.im.manager.RouterControlManager
import com.polaris.live.im.sfs.LIVE_GIFT_LIST
import com.polaris.live.im.sfs.LIVE_INVITE_SITE
import com.polaris.live.im.sfs.LIVE_KICK_ROOM
import com.polaris.live.im.sfs.LIVE_MAGIC_LAMP_90
import com.polaris.live.im.sfs.LIVE_MAGIC_LAMP_OPEN
import com.polaris.live.im.sfs.LIVE_PARTY_EMOJI
import com.polaris.live.im.sfs.LIVE_PUBLIC_SCREEN
import com.polaris.live.im.sfs.LIVE_SEND_GIFT
import com.polaris.live.im.sfs.LIVE_WARN_MESSAGE
import com.polaris.live.im.sfs.LUCKY_BACKPACK_GIFT
import com.polaris.live.im.sfs.NEW_COUPLES_FREE_GIFTS
import com.polaris.live.im.sfs.bean.live.LivePublicScreenMessage
import com.polaris.live.im.sfs.bean.live.LiveRoomInfo
import com.polaris.live.im.sfs.bean.live.SendLiveCloseMessage
import com.polaris.live.im.sfs.bean.live.SendLiveFloatingMessage
import com.polaris.live.im.sfs.bean.live.SendLiveMessage
import com.polaris.live.im.sfs.bean.live.ext.LiveEnterBean
import com.polaris.live.im.sfs.bean.live.ext.MessageUserExtBean
import com.polaris.live.im.sfs.bean.live.ext.UserBasicVo
import com.polaris.live.im.sfs.bean.live.payload.GiftListPayloadBean
import com.polaris.live.im.sfs.bean.live.payload.InviteGiftPayloadBean
import com.polaris.live.im.sfs.bean.live.toUserBasic
import com.polaris.live.im.sfs.core.SmartFoxManager
import com.polaris.live.im.sfs.core.bean.DataArgument
import com.polaris.live.im.sfs.core.bean.getRoomId
import com.polaris.live.im.utils.SmartFoxUtils.parseVariables
import com.polaris.live.interface_bag.XpopupCallBackImpl
import com.polaris.live.manager.AppConfigManager
import com.polaris.live.popup.ContributionListPopup
import com.polaris.live.popup.GameListPopup
import com.polaris.live.popup.GamePlayWinPopup
import com.polaris.live.popup.GlobalPopupManager
import com.polaris.live.popup.MagicLampWinRewardPopup
import com.polaris.live.popup.VipBarrageWhatPopup
import com.polaris.live.popup.party.InteractionEmojiPopup
import com.polaris.live.popup.party.InvitingSeatNoticePopup
import com.polaris.live.popup.party.LivePartyDrawerPopup
import com.polaris.live.popup.party.RoomInfoSpectatorPopup
import com.polaris.live.popup.party.RoomManagementPopup
import com.polaris.live.popup.party.SeatSettingPopup
import com.polaris.live.resp.back_resp.DisplayUserBean
import com.polaris.live.resp.back_resp.GiftBean
import com.polaris.live.resp.back_resp.InfoOtherResp
import com.polaris.live.resp.back_resp.LiveEmojiResp
import com.polaris.live.resp.back_resp.toDisplayUserBean
import com.polaris.live.resp.back_resp.toUserBasicVo
import com.polaris.live.resp.bean.MagicLampCountDownBean
import com.polaris.live.resp.go_resp.SendGiftBean
import com.polaris.live.translation.R
import com.polaris.live.ui.game.GameUtils
import com.polaris.live.ui.live.bean.LiveInitInfo
import com.polaris.live.ui.live.proxy.LivePublicProxy
import com.polaris.live.ui.live.proxy.gift.EntryScreenAnimationProxy
import com.polaris.live.ui.live.proxy.gift.GiftAnimationProxy
import com.polaris.live.ui.live.widget.LiveFloatView
import com.polaris.live.ui.live.widget.listener.OnPartySeatListener
import com.polaris.live.ui.live.widget.listener.OnSendPartyMessageListener
import com.polaris.live.ui.message.fragment.MessageSessionFragment
import com.polaris.live.ui.message.fragment.dialog.MessageSessionDialogFragment
import com.polaris.live.ui.message.fragment.dialog.MessageSingleDialogFragment
import com.polaris.live.ui.party.fragment.base.BasePartySpectatorFragment
import com.polaris.live.ui.party.listener.PartyImListener
import com.polaris.live.ui.party.utils.GiftDialogProxy
import com.polaris.live.ui.party.utils.GiftGivingAnimationProxy
import com.polaris.live.ui.party.widget.PartyBottomView
import com.polaris.live.ui.party.widget.seat.SeatBeanUtil
import com.polaris.live.ui.party.widget.seat.bean.SeatBean
import com.polaris.live.ui.party.widget.seat.listener.PartySeatListener
import com.polaris.live.utils.LiveUtils
import com.polaris.live.utils.StartLiveProxy
import com.polaris.live.utils.StartLiveProxy.permissionAudio
import com.polaris.live.utils.TaskRedListener
import com.polaris.live.utils.TaskRedProxy
import com.polaris.live.utils.XPopupUtils
import com.polaris.live.utils.fragment.showNewDialogFragment
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.route.RoutePath
import com.polaris.live.utils.route.Router
import com.polaris.live.utils.route.RouterUtils
import com.polaris.live.utils.zego.media.MediaProxy
import com.polaris.live.viewmodel.party.PartySpectatorFragmentModel
import com.polaris.live.widget.bubble.DownLoadFileUtil
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.libpag.PAGFile
import org.libpag.PAGScaleMode
import sfs2x.client.core.SFSEvent
import sfs2x.client.entities.variables.RoomVariable

/**
 * PartySpectatorFragment
 * @author Created by 天晴 on 2024/2/24 11:37
 * @since 1.0.0
 **/
class PartySpectatorFragment : BasePartySpectatorFragment<PartySpectatorFragmentModel, FragmentPartySpectatorBinding>(),
    PartyImListener, OnPartySeatListener {

    private var mLiveInfo: LiveRoomInfo? = null

    //被禁言的人
    private val mBanMessageUser = mutableListOf<Long>()

    //房管
    private val mAdministrators = mutableListOf<Long>()

    private val mEntryScreenAnimationProxy by lazy {
        EntryScreenAnimationProxy(
            requireActivity(),
            mBinding.entryFloatingScreen,
            mBinding.entryScreen,
            viewLifecycleOwner
        )
    }

    //礼物列表消息  延迟后添加快捷礼物列表
    private var mGiftJob: Job? = null

    //礼物代理
    private var mGiftProxy: GiftAnimationProxy? = null

    private var mEmojiList: List<LiveEmojiResp>? = null

    //礼物轮盘代理
    private val mGiftDialogProxy by lazy {
        mLiveInfo?.let { da ->
            GiftDialogProxy(requireContext(), mViewModel, da, mBinding.icRun, false)
                .apply {
                    setOnUserProfileClickListener {//礼物轮盘点击查看礼物
                        showPartyUserProfilePopup(it, true)
                    }
                }

        }
    }

    private val mSessionFragment by lazy { MessageSessionDialogFragment() }

    private val mLivePublicProxy by lazy {
        LivePublicProxy(requireContext(), mViewModel)
    }

    private val mLivePartyDrawerPopup: LivePartyDrawerPopup by lazy {
        LivePartyDrawerPopup(
            requireActivity(),
            onToLive = {
                mLivePartyDrawerPopup.dismiss()
                nextData(it)
            }, onToParty = {
                mLivePartyDrawerPopup.dismiss()
                GlobalPopupManager.showCompletePopup(requireContext(), isOk = {
                    mViewModel.getPartyRoom()
                })
            }
        )
    }
    private val mGiftGivingAnimationProxy by lazy {
        GiftGivingAnimationProxy(mViewModel, this)
    }

    private var lastBackground: String? = null //最后设置的背景

    private var minimize = false  //是否最小化

    /**
     * 底部控制
     */
    private val mBottomBuilder by lazy {
        PartyBottomView.Builder()
            .setShowMessageButton(true)
            .setShowSendrButton(true)
            .setShowGiftButton(true)
            .setShowSettingButton(true)
            .setFreeGiftSourceType(AppConst.BackpackGiftComming.PARTY)
            .setShowEmojiButton(false)
            .setShowGameButton(!GameUtils.getLiveCacheGameList().isNullOrEmpty())
            .setEmojiClickBack {
                showInteractionEmojiPopup()
            }
            .setMessageClickBack {
                showChatMessage()
            }
            .setSendrClickBack {
                mEditView?.showKeyboard()
            }
            .setGameClickBack {
                showGameList()
            }
            .setMikeStateBack { //开关音频
                mLiveInfo?.let { li ->
                    mViewModel.siteMicSwitch(li.userId, it == 1)
                }
            }
            .setGiftClickBack {
                showGiftDialog()
            }
            .setSettingClickBack {
                showRoomManagementPopup()
            }
            .setFreeGiftClickBack { gift ->
                val seatData = mBinding.partySeat.getSeatData().filter { it.userBasicVo != null }.toMutableList()
                if (CollectionUtils.isNotEmpty(seatData)) {
                    //如果麦位上只有自己
                    if (seatData.size == 1 && mBinding.partySeat.getMeSeatBean() != null) {
                        ToastGravity.showGravity(R.string.this_gift_dont_send_myself)
                    } else {
                        SendFreeGiftSelectDialog.show(requireContext(), seatData) {
                            mLiveInfo?.liveId?.let { liveId ->
                                mViewModel.sendFreeGift(it, gift, AppConst.BackpackGiftComming.PARTY, liveId)
                            }
                        }
                    }
                } else {//麦位没有人
                    ToastGravity.showGravity(R.string.seat_not_have_people)
                }
            }
    }

    override fun needShowViews() = listOf(
        mBinding.vMessage,
        mBinding.bottom.mBinding.sendr,
        mBinding.vHeader.mBinding.rvRecycler,
        mBinding.entryFloatingScreen,
        mBinding.widgetRoomBanner
    )

    override fun nextData(displayUserBean: DisplayUserBean) {
        if (displayUserBean.base.userId != mLiveInfo?.userId) {
            if (mBinding.partySeat.getMeSeatBean() != null) {
                ToastGravity.showGravity(R.string.sure_exit_party_tips)
            } else {
                mOnSpectatorFragmentListener?.nextData(displayUserBean)
            }

        }
    }

    /**
     * 执行最小化
     */
    override fun onMinimize() {
        minimize = true
        mOnSpectatorFragmentListener?.onMinimize(true)
        mBinding.partySeat.setMinimize(true)
        mBinding.partySeat.getPartyStreamProxy()?.let { psp ->
            mLiveInfo?.let { info ->
                FloatingWindowManager.showFloatingWindow(
                    FloatingService(
                        false,
                        info,
                        psp,
                        mBinding.partySeat.getSeatData(),
                        mBinding.vMessage.getAllMessageList(),
                        null,
                        password
                    )
                )
            }
        }
        mOnSpectatorFragmentListener?.closeActivity()
    }

    override fun roomType() = PARTY_VOICE_ROOM

    override fun showRightPopup() {
        mLivePartyDrawerPopup.chageToParty()
        XPopup.Builder(requireContext())
            .isViewMode(true)
            .hasShadowBg(false)
            .popupPosition(PopupPosition.Right)
            .setPopupCallback(object : XpopupCallBackImpl {
                override fun onDismiss(popupView: BasePopupView) {
                }
            })
            .asCustom(mLivePartyDrawerPopup)
            .show()
    }

    override fun onHideView(pd: Boolean) {
        mGiftProxy?.clearScreen(pd)
    }

    /**
     * =========================Im消息回调==================
     */
    override fun closeRoomMessage(da: SendLiveCloseMessage) {
        mOnSpectatorFragmentListener?.closeActivity(da)
    }

    override fun variableUpdate(variable: RoomVariable) {
        val liveInfo = mLiveInfo ?: return
        LiveUtils.fillLiveInfo(liveInfo, variable)

        SeatBeanUtil.getSeatId(variable.name)?.let {
            mBinding.partySeat.setUpdateDateSeat(it, liveInfo)
        }
        when (variable.name) {
            "showGainCoins" -> {
                mBinding.contributionView.showGainCoins((liveInfo.showGainCoins?.formatNumberWithK()) ?: "0")
            }

            "banMessageUser" -> {
                upDataBanMessage(liveInfo)
            }

            "administrator" -> {
                upDataAdministrator(liveInfo)
            }

            "background" -> {
                val background = liveInfo.background
                if (background.isNullOrEmpty()) {
                    lastBackground = background
                    // 如果背景为空，设置默认背景图像，并调整可见性
                    setDefaultBackground(liveInfo.theme)
                } else if (background != lastBackground) {
                    lastBackground = background
                    // 如果背景不为空且与上一个背景不同，设置新背景
                    setBackground(background, liveInfo.theme)
                }
            }
            "roomTheme" -> {
                setSkinUi()
            }
        }
    }

    override fun userCountChange(count: Int) {
    }

    override fun publicMessage(message: SendLiveMessage) {
        if (message.type in ImLiveManager.publicTypes && message.businessId == mLiveInfo?.liveId) {
            mBinding.vMessage.addMessage(message)
            if (message.type == LIVE_PUBLIC_SCREEN) {
                val ext = message.ext as? MessageUserExtBean?
                if (ext?.type == 1) { //发送的弹幕消息
                    mBinding.barrageView.addMessage(message)
                }
            }
        }
        //其他消息处理
        when (message.type) {
            LIVE_SEND_GIFT, LUCKY_BACKPACK_GIFT -> {
                mGiftGivingAnimationProxy.sendGiftEffect(requireContext(), message, mBinding.partySeat.getSeatData())
                mGiftProxy?.addAnimation(message)
                val ext = message.ext as MessageUserExtBean
                val payload = message.payload as InviteGiftPayloadBean
                payload.gift.animation?.let { mBinding.widgetGift.setGift(payload) }

                val isWinning = payload.reward != null && payload.reward.times > 0

                if (isWinning && UserManager.getUserId() == ext.user.userId) {
                    if (message.type != LUCKY_BACKPACK_GIFT) {
                        GlobalDialogManager.showUserWinning(requireContext(), payload)
                    } else {
                        GlobalDialogManager.showBackPackUserWinning(requireContext(), payload)
                    }
                }
            }

            //警告消息
            LIVE_WARN_MESSAGE -> {
                mLivePublicProxy.onPublicMessage(message)
            }
            //邀请上座信息
            LIVE_INVITE_SITE -> {
                showInvitingSeatNoticePopup(message)
            }

            LIVE_KICK_ROOM -> {
                ToastGravity.showGravity(message.content)
                mOnSpectatorFragmentListener?.closeActivity()
            }
            //礼物列表消息
            LIVE_GIFT_LIST -> {
                val payload = message.payload as GiftListPayloadBean
                val orNull = payload.gifts.getOrNull(0)
                orNull?.let {
                    playAnim(listOf(inAlpha(mBinding.widgetLiveFollower)))
                    mBinding.widgetLiveFollower.setData(
                        payload,
                        mLiveInfo?.avatar,
                        mLiveInfo?.userId
                    )
                    mGiftJob = lifecycleScope.launch(CoroutineScopeManager.ioDispatcher) {
                        delay(payload.duration * 1000)
                        withContext(CoroutineScopeManager.mainDispatcher) {
                            if (mBinding.widgetLiveFollower.isVisible) {
                                playAnim(listOf(outAlpha(mBinding.widgetLiveFollower)))
                            }
                        }
                    }
                }
            }
            //emoji消息
            LIVE_PARTY_EMOJI -> {
                mBinding.partySeat.showUserEmoji(message)
            }
            //神灯进度90%
            LIVE_MAGIC_LAMP_90 -> {
                mBinding.widgetRoomBanner.upDataMagicLamp()
            }
            //神灯开奖
            LIVE_MAGIC_LAMP_OPEN -> {
                val payload = message.payload as MagicLampCountDownBean
                mBinding.widgetRoomBanner.upDataMagicLamp()
                mBinding.widgetMagicLamp.addMagicLampPag(payload)
            }
            //新人免费礼物累计
            NEW_COUPLES_FREE_GIFTS -> {
                mBinding.bottom.inspectFreeGift()//检查是否累计免费礼物
            }
        }
    }

    override fun liveEvent(command: String, argument: DataArgument) {
        when (command) {
            SFSEvent.USER_ENTER_ROOM -> {
                val user = argument.getUser()
                //过滤自己和主播
                if (user == null
                    || user.name == UserManager.getUserId().toString()
                    || user.name == mLiveInfo?.liveId?.toString()
                ) {
                    return
                }
                argument.getUser()?.parseVariables<LiveEnterBean>()?.let {
                    mEntryScreenAnimationProxy.addEntryScreenOtherUser(it) {
                        mBinding.vEnter.addEnterBean(it)
                    }
                }
            }

            SFSEvent.USER_EXIT_ROOM -> {
                val user = argument.getUser()
                if (user == null || user.name == UserManager.getUserId().toString()) {
                    return
                }
                mEntryScreenAnimationProxy.removeEntryScreen(user.name.toLong())

            }
            //如果是加入则刷新直播间的信息
            SFSEvent.ROOM_JOIN -> {
                argument.getRoom()?.also { room ->
                    if (room.getRoomId().toString() == mAnchorId.toString()) {
                        room.variables.forEach {
                            variableUpdate(it)
                        }
                    }
                }
                SmartFoxManager.getLiveMyself()?.parseVariables<LiveEnterBean>()?.let {
                    mEntryScreenAnimationProxy.addEntryScreenMe(it)
                }
            }
        }
    }

    override fun floatingMessage(message: SendLiveFloatingMessage) {
        mBinding.widgetFloat.addFloatView(message)
    }

    /**
     * =========================Im消息回调END==================
     */

    private fun initImmersionBar() {
        ImmersionBar.with(this)
            .transparentBar()
            .titleBarMarginTop(mBinding.heardLl)
            .init()

        NavigationBarUtils.setNavigationHeight(mBinding.bottom)
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        initImmersionBar()
        mAnchorId = arguments?.getLong("anchorId", -1L) ?: -1
        mBinding.apply {
            bottom.initialize(mBottomBuilder, mViewModel)
            contributionView.showGainCoins(mLiveInfo?.showGainCoins?.formatNumberWithK() ?: "0")
        }

        initObserve()
        initListener()
        loading()
        if (resources.configuration.layoutDirection == View.LAYOUT_DIRECTION_RTL) {
            mBinding.close.scaleX = -1f
            mBinding.close.setPadding(10.dp, 0, 0, 0)
        }
        //适配小屏幕手机
        if (ScreenUtils.getScreenHeight() < 2000) {
            val lp = mBinding.vMessage.layoutParams as ViewGroup.MarginLayoutParams
            lp.height = 220.dp
            mBinding.vMessage.layoutParams = lp
        }

        mViewModel.openClearTimeJob()
        mViewModel.getBackGiftRed()
        mBinding.actMarquee.getActivitiesScroll(mViewModel, mAnchorId)
    }

    private fun initObserve() {
        mViewModel.clearTimeLiveData.observe(this) { _ ->
            mGiftGivingAnimationProxy.clearOverTimeQueue()
        }
        //游戏排行榜
        mViewModel.gameRankLiveData.observe(this) { resultState ->
            parseState(resultState, {
                if (!GameUtils.gameRun) {
                    mLiveInfo?.liveId?.let { id ->
                        GameUtils.putShowLiveId(id)
                    }
                    val tempContext = context
                    if (CollectionUtils.isNotEmpty(it) && tempContext != null) {
                        GamePlayWinPopup.show(tempContext, it) {
                            if (mLiveInfo?.userId != UserManager.getUserId()) { //主播不能点击
                                val roomId = (mLiveInfo?.userId ?: "").toString()
                                GameListPopup.show(tempContext, GameUtils.getLiveCacheGameList(), roomId)
                            }
                        }
                    }
                }
            })
        }
        //关注主播
        mViewModel.liveFollowLiveData.observe(this) { resultState ->
            parseState(resultState, {
                ToastGravity.showGravity(R.string.follower_succeed)
                clearFollower()
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }
        //关注房间
        mViewModel.followRoomLiveData.observe(this) { resultState ->
            parseState(resultState, {
                ToastGravity.showGravity(R.string.follower_succeed)
                mBinding.vHeader.updateFollowStatus(true)
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }

        //获取礼物飘屏用户信息
        mViewModel.giftInfoLiveData.observe(this) { resultState ->
            parseState(resultState, { user ->
                when (user.live?.liveType) {
                    LiveConst.Type.PARTY_LIVE, LiveConst.Type.VIDEO_PARTY -> {
                        nextData(user.toDisplayUserBean())
                    }

                    LiveConst.Type.PARTY_GAME_LIVE -> {
                        Router.builder(RoutePath.PARTY_GAME_SPECTATOR_ACTIVITY)
                            .withLong(LiveConst.Params.ANCHORID, user.userId)
                            .navigation(requireContext())
                    }

                    else -> {
                        if (user.live?.living == true) {
                            LiveUtils.toSpectator(user).navigation(requireActivity())
                            mOnSpectatorFragmentListener?.closeActivity()
                        }

                    }
                }

            })
        }
        //获取房间关注
        mViewModel.isFollowRoomLiveData.observe(this) { resultState ->
            parseState(resultState, { follow ->
                mBinding.vHeader.setUserFollower(follow)
            })
        }

        //获取游戏列表
        mViewModel.gameLiveData.observe(this) { resultState ->
            parseState(resultState, { it ->
                mBinding.bottom.showGameButton(it.isNotEmpty())
                GameUtils.setLiveCacheGameList(it)
                mLiveInfo?.liveId?.let { liveId ->
                    mViewModel.gameRank(liveId)
                }

            })
        }

        //直播获取顶部消费列表
        mViewModel.liveConsumeLiveData.observe(this) { (liveId, it) ->
            if (mLiveInfo?.liveId == liveId) {
                mBinding.vHeader.updateConsumeList(it)
                mBinding.widgetRoomBanner.upDataMagicLamp()
            }
        }
        //活动滚动信息刷新
        mViewModel.activitiesScrollLiveData.observe(this) {
            mLiveInfo?.let { info ->
                mBinding.actMarquee.getActivitiesScroll(mViewModel, info.userId)
            }
        }
        //点击隐藏edit
        ViewUtils.registerTouchDown(mBinding.widgetGift) {
            mEditView?.hideKeyboard()
        }
        //获取emoji列表
        mViewModel.mEmojiListLiveData.observe(this) { resultState ->
            parseState(resultState, {
                mEmojiList = it
                showInteractionEmojiPopup()
            })
        }
        //路由监听
        RouterControlManager.observeListener(this) { key, ext ->
            if (isVisibleToUser) {
                withLoaded {
                    when (key) {
                        RouterControlManager.ROUTER_ROOMGAME -> { //打开幸运游戏列表
                            val gameId = ext["gameId"]?.toLongOrNull()
                            if (gameId == null) {
                                showGameList()
                            } else {
                                val gameVo = GameUtils.getLiveCacheGameList()
                                    ?.asSequence()
                                    ?.flatMap { it.list.asSequence() }
                                    ?.find { it.gameID == gameId }
                                if (gameVo != null) {
                                    val roomId = mLiveInfo?.userId.toString()
                                    GameUtils.showGameFragment(requireContext(), gameVo, roomId = roomId)
                                } else {
                                    showGameList()
                                }
                            }
                        }

                        RouterControlManager.ROUTER_GIFT -> { //礼物盘拉起
                            val giftType = ext["giftType"]?.toIntOrNull()
                            mGiftDialogProxy?.showGiftPopup(
                                seatList = mBinding.partySeat.getSeatData(),
                                giftType = giftType
                            )
                        }

                        RouterControlManager.ROUTER_UP_MIC -> { //上麦
                            mBinding.partySeat.getNoHavaSeat()?.let { showSitePop(it) }
                        }
                    }
                }
            }
        }
        mViewModel.mBackGiftRedData.observe(this) { resultState ->
            parseState(resultState, {
                mBinding.bottom.setBackPackRed(if (it) View.VISIBLE else View.GONE)
            })
        }
        mViewModel.mPartyRoomLiveData.observe(this) { resultState ->
            parseState(resultState, {
                if (it.roomId?.isNotEmpty() == true) {
                    val liveType = UserManager.getUser().live?.liveType
                    StartLiveProxy.builder(this)
                        .recoverLive(mViewModel, liveType, it.roomId) {
                            mOnSpectatorFragmentListener?.closeActivity()
                        }
                } else {
                    Router.builder(RoutePath.SET_PARTY_COVER_ACTIVITY)
                        .navigation(requireActivity())
                }
            })
        }
        TaskRedProxy.observe(this, object : TaskRedListener {
            override fun updateRed(isRed: Boolean) {
                mBinding.bottom.setSettingRed(if (isRed) View.VISIBLE else View.GONE)
            }
        })
        mViewModel.mLampLotteryLiveData.observe(this) { resultState ->
            parseState(resultState, {
                MagicLampWinRewardPopup.show(requireContext(), it)
            }) {
                ToastGravity.showGravity(it.errorMsg)
            }
        }
        mBinding.widgetMagicLamp.openMagicLampCallBack {
            mLiveInfo?.userId?.let { userId ->
                mViewModel.lampLottery(userId, it.index.toLong())
            }
        }
        //免费礼物
        mViewModel.mSendFreeGiftLiveData.observe(this) {
            mBinding.bottom.inspectFreeGift()
        }
        //更新弹幕信息
        mViewModel.barrageNumberLiveData.observe(this) { resultState ->
            parseState(resultState, {
                mEditView?.upBarrage(it)
            })
        }
    }

    private fun initListener() {
        mBinding.apply {
            /**
             * 观众点击了，吊起礼物盘
             */
            actMarquee.setGiftIdBackListener {
                mGiftDialogProxy?.showGiftPopup(mLiveInfo?.toUserBasic(), it)
            }
            //直播间飘屏被点击
            widgetFloat.setOnSingleClickListener { data ->
                when (data.type) {
                    LiveFloatView.GIFT -> { //礼物飘屏
                        val seatBean =
                            mBinding.partySeat.getSeatBeanByUserId(UserManager.getUserId())
                        if (seatBean != null) {
                            ToastGravity.showGravity(R.string.sure_exit_party_tips)
                            return@setOnSingleClickListener
                        }
                        RouterUtils.getAnchorId(data.router)?.let { id ->
                            if (mAnchorId != id) {
                                mViewModel.getGiftInfoUser(id)
                            }
                        }
                    }

                    LiveFloatView.GAME -> { //游戏中奖
                        GameUtils.showAndCheckGameFragment(
                            requireContext(),
                            mLiveInfo?.userId,
                            data.payload
                        )
                    }

                    LiveFloatView.ROOM -> { //开房通知
                        data.router?.let {
                            val pathUrl = RouterUtils.routerGetPath(it)
                            RouterUtils.killTopActivity(it, pathUrl)
                        }
                    }
                    LiveFloatView.GENERAL -> { //通用
                        data.router?.let {
                            RouterUtils.routerGoto(it)
                        }
                    }
                }
            }
            //直播间用户列表
            vHeader.setOnConsumeItemClickListener { _, item ->
                if (item.userId == UserManager.getUserId()) {
                    showPartyUserProfilePopup(item.userId, true)
                } else {
                    mGiftDialogProxy?.showGiftPopup(
                        UserBasicVo(
                            userId = item.userId,
                            avatar = item.avatar,
                            avatarFrame = item.avatarFrame,
                            userNumber = 0,
                            sex = AppConst.UserSex.NONE,
                            nickname = "",
                            createTime = 0,
                            richs = 0,
                            charms = 0
                        )
                    )
                }
            }
            //点击主播头像
            vHeader.setOnAvatarClientListener {
                showRoomInfoPopup()
            }
            //点击关注
            vHeader.setOnFollowerClickListener {
                mLiveInfo?.userId?.also { userId ->
                    mViewModel.addFollowRoom(userId)
                }
            }
            //点击在线人数
            vHeader.setOnOnlineClickListener {
                mLiveInfo?.let {
                    GlobalPopupManager.showOnRoomUser(requireContext(), this@PartySpectatorFragment, mViewModel,
                        it.liveId, it.userId,
                        LiveConst.Type.PARTY_LIVE,
                        mAdministrators,
                        onHeadClickListener = { userId ->
                            showPartyUserProfilePopup(userId, true)
                        }, onSendGiftSomeOneCallback = { userBase ->
                            if (userBase == null) {
                                showGiftDialog()
                            } else {
                                if (userBase.userId != UserManager.getUserId()) {
                                    mGiftDialogProxy?.showGiftPopup(userBase)
                                }
                            }
                        })
                }
            }

            //赠送礼物
            vMessage.mBinding.baseMessage.setOnSendGiftListener {
                mViewModel.sendGift(requireContext(), it, LiveConst.SendGift.publicGift)
            }
            //赠送关注礼物
            vMessage.mBinding.baseMessage.setOnSendFollowerListener {
                mViewModel.sendGift(requireContext(), it, LiveConst.SendGift.followerGift)
            }
            //点击屏幕中间关注礼物
            widgetLiveFollower.setOnCallSendGiftList { gift, type ->
                sendGift(gift, type)
            }
            /**
             * 上座信息
             */
            vMessage.mBinding.baseMessage.setOnSendUpSeatListener {
                upSeat(false, null)
            }
            //公屏举报
            vMessage.mBinding.baseMessage.setOnReportListener {
                if (it.ext is MessageUserExtBean) {
                    GlobalPopupManager.showReport(
                        requireContext(), it.ext.user.nickname,
                        mViewModel, it.ext.user.userId, mLiveInfo?.liveId
                    )
                }
            }
            //显示头像
            vMessage.mBinding.baseMessage.setOnUserProfileClickListener {
                showPartyUserProfilePopup(it, true)
            }
            close.setOnSingleClickListener {
                if (!onBackPressed()) {
                    mOnSpectatorFragmentListener?.closeActivity()
                }

            }
            /**
             * 座位回调
             */
            partySeat.setPartySeatListener(object : PartySeatListener {
                /**
                 * 被点击
                 */
                override fun clickItem(index: Int, seatBean: SeatBean) {
                    //有人
                    if (seatBean.userBasicVo != null) {
                        seatBean.userBasicVo?.userId?.let {
                            if (it == UserManager.getUserId()) {
                                showPartyUserProfilePopup(it, false, seatBean)
                            } else {
                                mGiftDialogProxy?.showGiftPopup(seatBean.userBasicVo)
                            }
                        }
                    } else {
                        val find = mAdministrators.find { it == UserManager.getUserId() }
                        if (find != null) {
                            showSeatPopup(seatBean)
                        } else {
                            showSitePop(seatBean)
                        }
                    }
                }

                override fun updateOneSelfSeat(seatBean: SeatBean?) {
                    if (seatBean == null || seatBean.siteMicStatus != 1) {
                        MediaProxy.closeMusic()
                    }
                    mOnSpectatorFragmentListener?.prohibitSliding(seatBean != null, true)
                    mBinding.bottom.apply {
                        if (seatBean == null) {
                            showMikeButton(false)
                            showEmojiButton(false)
                        } else {
                            setMikeState(seatBean.siteMicStatus ?: 1)
                            showMikeButton(true)
                            showEmojiButton(true)
                        }
                    }

                }

                override fun soundLevelUpdate(seatId: Int, soundLevel: Float) {
                    mLiveInfo?.let {
                        mViewModel.taskMicReport(it.liveId.toString(), seatId.toLong(), soundLevel.toString())
                    }

                }
            })

            /**
             * 点击贡献榜
             */
            contributionView.setOnSingleClickListener {
                ContributionListPopup.showPop(requireContext(), this@PartySpectatorFragment, mViewModel, mAnchorId) {
                }
            }
            widgetRoomBanner.setOnTouchCallback {
                mOnSpectatorFragmentListener?.onBannerTouch(it)
            }
            widgetRoomBanner.setMagicLampListener {
                mLiveInfo?.let { info ->
                    MagicLampPopup.show(this@PartySpectatorFragment, mViewModel, info.userId, false) {
                        mGiftDialogProxy?.showGiftPopup(seatList = mBinding.partySeat.getSeatData())
                    }
                }

            }
            barrageView.addReportCallBack {
                GlobalPopupManager.showReport(
                    requireContext(),
                    it.nickname,
                    mViewModel,
                    it.userId,
                    it.userId
                )
            }
        }

    }

    private fun clearFollower() {
        mBinding.vMessage.mBinding.baseMessage.clearFollower()
    }

    //赠送关注礼物
    private fun sendGift(gift: GiftBean, type: Int) {
        val userId = mLiveInfo?.userId
        val liveId = mLiveInfo?.liveId
        if (userId != null && liveId != null) {
            val sendGiftBean = SendGiftBean(
                recipient = userId,
                giftId = gift.id,
                count = 1,
                sourceType = AppConst.GiftComming.CALL,
                objectId = liveId,
                payload = gift.payload
            )
            mViewModel.sendGift(requireContext(), sendGiftBean, type)

            if (type == LiveConst.SendGift.followerGift) {
//                mBinding.vHeader.updateFollowStatus(true)
            }
            if (mBinding.widgetLiveFollower.isVisible) {
                mGiftJob?.cancel()
                playAnim(listOf(outAlpha(mBinding.widgetLiveFollower)))
            }
        }
    }

    private fun setDefaultBackground(theme: Int?) {
        mBinding.bgImg.visibility = View.VISIBLE
        mBinding.bgPag.visibility = View.GONE
        mBinding.bgPag.stop()
        Glide.with(requireContext())
            .load(getDefaultDrawable(theme))
            .into(mBinding.bgImg)
    }

    private fun getDefaultDrawable(theme: Int?): Int {
        return when (theme) {
            LiveConst.THEME_TYPE.LIVE_PARTY_THEME_COUPLE -> drawable.party_cp_bg
            LiveConst.THEME_TYPE.LIVE_PARTY_THEME_EMPEROR -> drawable.party_emperor_bg
            LiveConst.THEME_TYPE.LIVE_PARTY_THEME_HONOR -> drawable.party_birthday_bg
            LiveConst.THEME_TYPE.LIVE_PARTY_THEME_SUPREME -> drawable.party_birthday_bg
            LiveConst.THEME_TYPE.LIVE_PARTY_THEME_AMUSEMENT -> drawable.just_party_back
            else -> drawable.just_party_back
        }
    }

    private fun setBackground(background: String, theme: Int?) {
        val cleanUrl = background.substringBefore("?")
        if (cleanUrl.endsWith(PagConst.PAG)) {
            mBinding.bgImg.visibility = View.VISIBLE
            DownLoadFileUtil.loadPag(lifecycleScope, cleanUrl) { pagPath, localPath ->
                lastBackground?.let {
                    val nowBgPath = it.substringBefore("?")
                    if (pagPath == nowBgPath) { //相同的背景才显示
                        mBinding.bgPag.apply {
                            composition = PAGFile.Load(localPath)
                            setScaleMode(PAGScaleMode.Zoom)
                            setRepeatCount(-1)
                            if (!isPlaying) {
                                play()
                            }
                        }
                        mBinding.bgPag.visibility = View.VISIBLE
                        mBinding.bgImg.visibility = View.GONE
                    }
                }
            }
        } else {
            mBinding.bgImg.visibility = View.VISIBLE
            mBinding.bgPag.visibility = View.GONE
            mBinding.bgPag.stop()
            Glide.with(requireContext())
                .load(ImageUtils.imgPath(cleanUrl))
                .placeholder(getDefaultDrawable(theme))
                .into(mBinding.bgImg)
        }
    }

    /**
     * 显示房间管理RoomManagement
     */
    private fun showRoomManagementPopup() {
        XPopup.Builder(requireContext())
            .isViewMode(true)
            .hasShadowBg(false)
            .moveUpToKeyboard(false)
            .isDestroyOnDismiss(true)
            .asCustom(
                mLiveInfo?.let {
                    RoomManagementPopup(requireContext(), false, 0, false, false,
                        it, mViewModel, mBinding.widgetGift.getIsOpenGift(), mBinding.widgetGift.getIsOpenSound(),
                        onOpenGiftAnimation = {
                            mBinding.widgetGift.setIsOpenGiftAnimation(it)
                            mBinding.widgetMagicLamp.setIsOpenGiftAnimation(it)
                        }, onOpenGiftSound = {
                            mBinding.widgetGift.setIsOpenSound(it)
                        }, music = {
                            MusicPopup.show(this@PartySpectatorFragment) {
                                upSeat(false, null)
                            }
                        }, onMinimize = {
                            onMinimize()
                        }, onInvitationFriend = {
                            mLiveInfo?.liveId?.let { liveId ->
                                val fragmentManager = childFragmentManager
                                RoomInvitationFragmentDialog().apply {
                                    arguments = bundleOf("liveId" to liveId)
                                }.show(
                                    fragmentManager,
                                    "RoomInvitationFragmentDialog"
                                )
                            }

                        })
                }
            )
            .show()
    }

    /**
     * 加入直播间成功
     */
    override fun initLiveInfo(data: LiveInitInfo, password: String?) {
        withLoaded {
            super.initLiveInfo(data, password)
            val variable = data.info
            mLiveInfo = variable
            mLiveInfo?.userId?.let {
                mBinding.partySeat.setInitJoinData(
                    variable, it,
                    FloatingWindowManager.getPartyStreamProxy(variable.roomId)
                )
            }
            mBinding.apply {
                vHeader.initData(pageType, variable, data.userCount)
                vMessage.initData(pageType, variable)
                mEditView?.initData(variable)
                widgetRoomBanner.initBannerData(lifecycle, mViewModel, variable.liveId, variable.userId)
                bottom.inspectFreeGift()//检查是否累计免费礼物
                CommonCache.getMagicLampList().forEach { widgetMagicLamp.addMagicLampPag(it) }
            }
            mGiftProxy = GiftAnimationProxy(this, requireContext(), mBinding.llGift, variable.nickname)
                .apply {
                    //礼物队列点击头像
                    setOnHeadOnClickListener {
                        showPartyUserProfilePopup(it, true)
                    }
                }
            mLiveInfo?.let { upDataBanMessage(it) }
            mLiveInfo?.let { upDataAdministrator(it) }


            mBinding.sourceCl.visibility = View.VISIBLE

            mViewModel.getFollowRoomUser(mAnchorId)


            mViewModel.getGameList(data.info.liveId)
            mViewModel.launchConsumeUser(data.info.liveId) //定时5秒请求一次  顶部消费列表

            //发送公屏消息
            mEditView?.setOnSendPartyMessageListener(object : OnSendPartyMessageListener {
                override fun onSendPublicMessage(message: LivePublicScreenMessage) {
                    mViewModel.sendPublicMessage(message)
                }

                override fun onBarrageWhat() {
                    VipBarrageWhatPopup.showPop(requireContext(), true) {
                        Router.instance.setPath(RoutePath.VIP_CENTER_ACTIVITY)
                            .withInt("page", 0)
                            .withInt("level", 6)
                            .navigation(requireContext())
                    }
                }
            })
            lastBackground = data.info.background
            lastBackground?.let {
                setBackground(it, data.info.theme)
            } ?: setDefaultBackground(data.info.theme)

            mGiftGivingAnimationProxy.initSeatViewAddr(
                mBinding.gifta, 0, -(20.autoDp), *mBinding.partySeat.getSeatViewAddr().toTypedArray()
            )
            mLiveInfo?.roomId?.let { id ->
                FloatingWindowManager.getMessage(id)?.reversed()?.forEach {
                    mBinding.vMessage.addMessage(it)
                }
            }
            setSkinUi()
        }
    }

    /**
     * 退出房间
     */
    override fun exitRoom() {
        if (!isCreated()) {
            return
        }

        super.exitRoom()
        mBinding.sourceCl.visibility = View.INVISIBLE
        stopJob()
        mViewModel.stopConsumeJob()
        mViewModel.cancelGameRankJob()
        mEditView?.reset()
        mBinding.apply {
            vHeader.reset()
            partySeat.reset()
            vMessage.reset()
            mGiftProxy?.reset()
            mGiftDialogProxy?.reset()
            mEntryScreenAnimationProxy.reset()
            actMarquee.reset()
        }

    }

    /**
     * 获取这个房间上座信息
     */
    override fun getIsRoomSeat(): Boolean {
        return mBinding.partySeat.getMeSeatBean() != null
    }

    override fun getIsGameMode(): Boolean {
        return false
    }

    /**
     * 显示房间信息
     */
    private fun showRoomInfoPopup() {
        mLiveInfo?.let {
            RoomInfoSpectatorPopup.show(
                this,
                it.liveId,
                it.userId,
                it.roomId ?: "",
                mLiveInfo?.vipLevel,
                mLiveInfo?.roomTheme, { userId ->
                    if (mLiveInfo?.userId == userId) { //点击房主
                        mGiftDialogProxy?.showGiftPopup(mLiveInfo?.toUserBasic())
                    } else {
                        showPartyUserProfilePopup(userId, true)
                    }
                }) { pd ->
                mBinding.vHeader.updateFollowStatus(pd)
            }
        }

    }

    /**
     * 显示资料卡片
     * search 是否查找座位上的人信息
     */
    private fun showPartyUserProfilePopup(
        userId: Long,
        search: Boolean = false,
        seatBean: SeatBean? = null,
    ) {
        val mutableSeatBean =
            seatBean ?: if (search) mBinding.partySeat.getSeatBeanByUserId(userId) else null
        GlobalPopupManager.showPartyUserProfilePopup(
            requireContext(),
            this,
            mViewModel,
            userId,
            UserConst.From.LIVE,
            mLiveInfo?.liveId,
            mLiveInfo?.userId,
            mutableSeatBean,
            onLeaveSeatClickListener = {
                mViewModel.liveSiteDown(mAnchorId)
            }, onGiftClickListener = {
                //点击送礼
                mGiftDialogProxy?.showGiftPopup(it.toUserBasicVo())
            }, onMessageClickListener = {
                showChatMessage(it.toUserBasicVo())
            }, onSelectMoreCardListener = {
                showSelectMoreCard(it)
            })
    }

    private fun showSelectMoreCard(infoUserResp: InfoOtherResp) {
        val mutableSeatBean = mBinding.partySeat.getSeatBeanByUserId(infoUserResp.userId)
        GlobalPopupManager.showSelectMoreCard(
            requireContext(),
            this,
            mViewModel,
            infoUserResp,
            mutableSeatBean,
            mBanMessageUser,
            mAdministrators,
            mLiveInfo?.liveId,
            mLiveInfo?.userId,
            false,
            onInviteOrKickSiteListener = {
                if (it) {
                    mLiveInfo?.liveId?.let { it1 -> mViewModel.partyInviteSite(infoUserResp.userId, null, it1) }
                } else {
                    //踢下座位
                    mLiveInfo?.userId?.let { it1 -> mViewModel.siteKick(infoUserResp.userId, it1) }
                }
            }, onKickRoomListener = {
                //踢出房间
                mLiveInfo?.userId?.let { mViewModel.kickUser(infoUserResp.userId, it, mLiveInfo?.roomId) }
            }, onAtClickListener = {
                mEditView?.atUser(infoUserResp.userId, infoUserResp.nickname)
            }
        )
    }

    private fun showGameList() {
        val roomId = (mLiveInfo?.userId ?: "").toString()
        GameListPopup.show(requireContext(), GameUtils.getLiveCacheGameList(), roomId)
    }

    /**
     * 显示Emoji管理
     */
    private fun showInteractionEmojiPopup() {
        if (mEmojiList == null) {
            mViewModel.emojiList()
            return
        }
        mEmojiList?.let {
            XPopupUtils.showViewPopup(
                InteractionEmojiPopup(requireContext(), it, mViewModel, {
                    mLiveInfo?.liveId?.let { it1 -> mViewModel.sendEmoji(it.id, it1) }
                }) {
                    mEmojiList = null
                }
            )
        }

    }

    /**
     * 邀请上座Pop
     */
    private fun showInvitingSeatNoticePopup(liveMessage: SendLiveMessage) {
        val context = context
        if (context != null) {
            InvitingSeatNoticePopup.show(
                context,
                liveMessage, {
                    mLiveInfo?.liveId?.let {
                        mViewModel.partyRejectSite(it)
                    }
                }
            ) {
                dismiss()
                upSeat(true, it)
            }
        }
    }

    /**
     * 上麦
     */
    private fun showSitePop(seatBean: SeatBean) {
        //麦位被锁不响应
        if (seatBean.siteLock != true) {
            permissionAudio(requireContext(), {
                upSeat(false, seatBean.seatId)
            })
        }
    }

    /**
     * 显示座位管理
     */
    private fun showSeatPopup(seatBean: SeatBean) {
        val userId = mLiveInfo?.userId ?: return
        val liveId = mLiveInfo?.liveId ?: return
        XPopup.Builder(requireContext())
            .isViewMode(true)
            .hasShadowBg(true)
            .isDestroyOnDismiss(true)
            .asCustom(
                SeatSettingPopup(
                    requireContext(), seatBean, mViewModel, userId, liveId
                ) {
                    showSitePop(seatBean)
                }
            )
            .show()
    }

    private fun upSeat(isInvite: Boolean, seatId: Int?) {
        permissionAudio(requireContext(), {
            mViewModel.liveSiteUp(mAnchorId, isInvite, seatId)
        })
    }

    private var inspectPublishJob: Job? = null

    /**
     * 延迟一秒检查推流情况,等打电话界面关闭推流再打开
     */
    private fun inspectPublishStream() {
        withLoaded {
            stopJob()
            inspectPublishJob = mViewModel.viewModelScope.launch {
                try {
                    delay(1000)
                    mBinding.partySeat.inspectMaishangZego()
                } finally {
                    if (inspectPublishJob == coroutineContext[Job]) {
                        inspectPublishJob = null
                    }
                }
            }
        }
    }

    private fun stopJob() {
        inspectPublishJob?.cancel()
    }

    //判断当时fragment是展示的还是隐藏的
    private var isVisibleToUser = false
    override fun onResume() {
        super.onResume()
        mBinding.partySeat.onResume()
        isVisibleToUser = true
        withLoaded {
            inspectPublishStream()
        }
    }

    override fun onPause() {
        super.onPause()
        isVisibleToUser = false
//        mBinding.partySeat.onPause()
        stopJob()
    }

    override fun onDestroyView() {
        exitRoom()
        mBinding.partySeat.destroyView()
        mViewModel.stopClearTimeJob()
        super.onDestroyView()
    }

    /**
     * 展示消息列表
     */
    private fun showChatMessage(userBase: UserBasicVo? = null) {
        if (userBase != null) {
            childFragmentManager.showNewDialogFragment(
                MessageSingleDialogFragment(
                    userBase.userId,
                    userBase.avatar,
                    userBase.avatarFrame,
                    userBase.chatBubble,
                    nestedPage = false,
                    singlePage = true
                ), MessageSessionFragment.FRAGMENT_TAG
            )
        } else {
            mSessionFragment.show(
                childFragmentManager,
                MessageSessionDialogFragment.FRAGMENT_TAG
            )
        }
    }

    override fun showGiftDialog() {
        withLoaded {
            mGiftDialogProxy?.showGiftPopup(seatList = mBinding.partySeat.getSeatData())
        }
    }

    override fun switchUserRoom(anchorId: Long?, childRouter: String?) {
        withLoaded {
            if (anchorId != null && anchorId != mLiveInfo?.userId) {
                mViewModel.getGiftInfoUser(anchorId)
            } else {
                childRouter?.let { RouterUtils.routerGoto(it) }
            }
        }
    }

    /**
     * 更新禁止发言用户
     */
    private fun upDataBanMessage(liveInfo: LiveRoomInfo) {
        mBanMessageUser.clear()
        liveInfo.banMessageUser?.let { banMessageUserJson ->
            val data: List<Long>? = JsonUtils.fromJson(banMessageUserJson)
            data?.let {
                mBanMessageUser.addAll(it)
            }
        }
    }

    /**
     * 更新管理员
     */
    private fun upDataAdministrator(liveInfo: LiveRoomInfo) {
        mAdministrators.clear()
        liveInfo.administrator?.let {
            val data: List<Long>? = JsonUtils.fromJson(it)
            if (data?.isNotEmpty() != null) {
                mLiveInfo?.userId?.let { it1 -> mBinding.partySeat.upDataUserPosition(data, it1) }
                mAdministrators.addAll(data)
            }
        }
    }

    /**
     * 更新皮肤
     */
    private fun setSkinUi() {
        val themeData = AppConfigManager.getUserTheme(mLiveInfo?.roomTheme)
        mBinding.partySeat.setTheme(themeData)
        mBinding.vHeader.setTheme(themeData)
        mBinding.bottom.setTheme(themeData)
    }

    companion object {

        private const val pageType = LiveConst.Page.LIVE_SPECTATOR
    }
}